//
//  MeTableViewController.m
//  WFChat UIKit
//
//  Created by WF Chat on 2017/11/4.
//  Copyright © 2017年 WildFireChat. All rights reserved.
//

#import "WFCMeTableViewController.h"
#import <WFChatClient/WFCChatClient.h>
#import <SDWebImage/SDWebImage.h>
#import <WFChatUIKit/WFChatUIKit.h>
#import "WFCSettingTableViewController.h"
#import "WFCSecurityTableViewController.h"
#import "WFCMeTableViewHeaderViewCell.h"
#import "UIColor+YH.h"
#import "WFCFavoriteTableViewController.h"
#import "WFCThemeTableViewController.h"
#import "YGExtendChain.h"
#import "SDAutoLayout.h"
#import "WFCBaseTabBarController.h"

 

@interface WFCMeTableViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UIImageView *portraitView;
@property (nonatomic, strong)NSArray *itemDataSource;

@property (nonatomic, strong)UIView * inputView ;


@end

#define Notification_Setting_Cell   0
#define Favorite_Settings_Cell      1
#define File_Settings_Cell 2
#define Safe_Setting_Cell 3
#define More_Setting_Cell 4
#define then_Setting_Cell 5
#define Dynamic_Cell      6

@implementation WFCMeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
//    self.view.backgroundColor = [WFCUConfigManager globalManager].backgroudColor;

   
    CGFloat wsf =  ZmScreenWidth_N()   ;
    CGFloat ws1 = wsf  / 360 * 407;

    
    UIImageView *head = [[UIImageView alloc]init];
    [self.view addSubview:head];
    head.image = [UIImage imageNamed:@"me_head"];
    head.contentMode = UIViewContentModeScaleToFill;
    head.sd_layout.rightEqualToView(self.view).topEqualToView(self.view).widthIs(ZmScreenWidth_N()).heightIs(ws1);

    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    if (@available(iOS 15, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.tableHeaderView = nil;
    [self.tableView reloadData];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.backgroundColor = [UIColor clearColor];
    if ([self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        if (@available(iOS 11.0, *)) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
    }
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 300)];
    header.backgroundColor = [WFCUConfigManager globalManager].naviBackgroudColor;
    self.tableView.tableHeaderView = header;
    self.tableView.contentInset = UIEdgeInsetsMake(-300, 0, 0, 0);
    [self.view addSubview:self.tableView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUserInfoUpdated:) name:kUserInfoUpdated object:nil];
    
    if ([[WFCCIMService sharedWFCIMService] isCommercialServer]) {
        self.itemDataSource = @[
            @{@"title":LocalizedString(@"Message"), @"image":@"notification_setting", @"type":@(Notification_Setting_Cell)},
            @{@"title":LocalizedString(@"Favorite"), @"image":@"favorite_settings", @"type":@(Favorite_Settings_Cell)},
            @{@"title":LocalizedString(@"File"), @"image":@"file_settings", @"type":@(File_Settings_Cell)},
            @{@"title":LocalizedString(@"AccountSafety"), @"image":@"safe_setting", @"type":@(Safe_Setting_Cell)},
            @{@"title":LocalizedString(@"Settings"), @"image":@"MoreSetting", @"type":@(More_Setting_Cell)}
        ];
    } else {
        self.itemDataSource = @[
            @{@"title":LocalizedString(@"AccountSafety"), @"image":@"safe_setting", @"type":@(Safe_Setting_Cell)},
            @{@"title":LocalizedString(@"我的朋友圈"), @"image":@"me_dynamic", @"type":@(Dynamic_Cell)},
            @{@"title":LocalizedString(@"MessageNotification"), @"image":@"notification_setting", @"type":@(Notification_Setting_Cell)},
            
            @{@"title":LocalizedString(@"Favorite"), @"image":@"favorite_settings", @"type":@(Favorite_Settings_Cell)},
            @{@"title":LocalizedString(@"主题"), @"image":@"then", @"type":@(then_Setting_Cell)},

            @{@"title":LocalizedString(@"Settings"), @"image":@"MoreSetting", @"type":@(More_Setting_Cell)}
        ];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
    self.navigationController.navigationBar.hidden = YES;
//    self.tableView.backgroundColor = [WFCUConfigManager globalManager].backgroudColor;
//    self.tableView.backgroundColor = [UIColor whiteColor];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)onUserInfoUpdated:(NSNotification *)notification {
    NSArray<WFCCUserInfo *> *userInfoList = notification.userInfo[@"userInfoList"];
    for (WFCCUserInfo *userInfo in userInfoList) {
        if ([[WFCCNetworkService sharedInstance].userId isEqualToString:userInfo.userId]) {
            [self.tableView reloadData];
            break;
        }
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.itemDataSource.count+1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    } else {
        return 0.f;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return nil;
    } else {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 9)];
        view.backgroundColor = [UIColor clearColor];
        return view;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0) {
        WFCMeTableViewHeaderViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"profileCell"];
        if (cell == nil) {
            cell = [[WFCMeTableViewHeaderViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"profileCell"];

        }
        
        WFCCUserInfo *me = [[WFCCIMService sharedWFCIMService] getUserInfo:[WFCCNetworkService sharedInstance].userId refresh:YES];
        cell.userInfo = me;
        cell.backgroundColor = [UIColor clearColor];
        cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@""]];
        cell.contentView.backgroundColor = [UIColor clearColor];
        __weak typeof(self) ws = self;
        
        [cell.portrait jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            [ws onViewPortrait:nil];
        }];
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"styleDefault"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"styleDefault"];
        }
        
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"right_arrow"]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];

        cell.textLabel.text = self.itemDataSource[indexPath.section - 1][@"title"];
        cell.imageView.image = [WFCUImage imageNamed:self.itemDataSource[indexPath.section - 1][@"image"]];
        cell.contentView.backgroundColor = [UIColor clearColor];
        return cell;
    }
    return nil;
}

- (void)onViewPortrait:(id)sender {
    WFCCUserInfo *me = [[WFCCIMService sharedWFCIMService] getUserInfo:[WFCCNetworkService sharedInstance].userId refresh:YES];

    WFCUMyPortraitViewController *pvc = [[WFCUMyPortraitViewController alloc] init];
    pvc.userId = me.userId;
//    [self.navigationController pushViewController:pvc animated:YES];
    pvc.modalPresentationStyle = UIModalPresentationFullScreen;
    [Zm_getCurrentVC() presentViewController:pvc animated:YES completion:nil];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 232;
    } else {
        return 50;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        WFCUMyProfileTableViewController *vc = [[WFCUMyProfileTableViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        int type = [self.itemDataSource[indexPath.section-1][@"type"] intValue];
        if (type == Notification_Setting_Cell) {
           WFCUMessageSettingViewController *mnvc = [[WFCUMessageSettingViewController alloc] init];
           mnvc.hidesBottomBarWhenPushed = YES;
           [self.navigationController pushViewController:mnvc animated:YES];
       } else if (type == Favorite_Settings_Cell) {
           WFCFavoriteTableViewController *mnvc = [[WFCFavoriteTableViewController alloc] init];
           mnvc.hidesBottomBarWhenPushed = YES;
           [self.navigationController pushViewController:mnvc animated:YES];
       } else if(type == File_Settings_Cell) {
           WFCUFilesEntryViewController *fevc = [[WFCUFilesEntryViewController alloc] init];
           fevc.hidesBottomBarWhenPushed = YES;
           [self.navigationController pushViewController:fevc animated:YES];
       } else if(type == Dynamic_Cell) {
           WFCUFUserCircleVC *fevc = [[WFCUFUserCircleVC alloc] init];
           fevc.hidesBottomBarWhenPushed = YES;
           fevc.userId = [WFCCNetworkService sharedInstance].userId ;
           [self.navigationController pushViewController:fevc animated:YES];
           
           
       } else if(type == then_Setting_Cell) {

//           WFCThemeTableViewController *vc = [[WFCThemeTableViewController alloc] init];
//           vc.hidesBottomBarWhenPushed = YES;
//           [self.navigationController pushViewController:vc animated:YES];
           
           
           [([UIApplication sharedApplication].keyWindow ?: [UIApplication sharedApplication].windows.firstObject) addSubview:self.inputView];
           self.inputView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));
           
           
           
       } else if(type == Safe_Setting_Cell) {
           WFCSecurityTableViewController * stvc = [[WFCSecurityTableViewController alloc] init];
           stvc.hidesBottomBarWhenPushed = YES;
           [self.navigationController pushViewController:stvc animated:YES];
       } else if(type == More_Setting_Cell) {
           WFCSettingTableViewController *vc = [[WFCSettingTableViewController alloc] init];
                  vc.hidesBottomBarWhenPushed = YES;
                  [self.navigationController pushViewController:vc animated:YES];
       }
    }
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    view.backgroundColor = [UIColor whiteColor];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

 

- (UIView *)inputView{
    if (!_inputView) {
        _inputView = [[UIView alloc]init];
        
        _inputView.sh_chain_extend.backgroundColor([UIColor colorWithHexString:@"#3F3C41" alpha:0.57]).addTarget_action(self, @selector(removeMain));

        UIView *view = [[UIView alloc]init];
        [_inputView addSubview:view];
        view.sd_layout.centerXEqualToView(self.inputView).centerYEqualToView(self.inputView).offset(-25) .widthIs(ZmScreenWidth_N() - 130) ;
        view.sh_chain_extend.backgroundColorWhite().roundSize(25);

        
        
      
   
         
         
        
      
        UIButton *btn1_c = [[UIButton alloc]init];
        [view addSubview:btn1_c];
        btn1_c.sd_layout.leftSpaceToView(view, 10).topSpaceToView(view, 20).heightIs(36).widthIs(140);
        btn1_c.sh_chain_extend.title(@"浅色主题").titleColor([UIColor colorWithHexString:@"#2B2136"]).font_size(17).addTarget_action(self, @selector(on1Register));
      
        UIView *lab1 = [[UIView alloc]init];
        
        [view addSubview:lab1];
        lab1.sd_layout.topSpaceToView(btn1_c, 5).leftSpaceToView(view, 5).rightSpaceToView(view, 5).heightIs(1) ;
 
        lab1.sh_chain_extend.backgroundColorLight();
        
        
        
        
        UIButton *btn1_d = [[UIButton alloc]init];
        [view addSubview:btn1_d];
        btn1_d.sd_layout.leftSpaceToView(view, 10).topSpaceToView(lab1, 10).heightIs(36).widthIs(140);
        btn1_d.sh_chain_extend.title(@"深色主题").titleColor([UIColor colorWithHexString:@"#2B2136"]).font_size (17).addTarget_action(self, @selector(on2Register));
        
        
        
        
        [view setupAutoHeightWithBottomView:btn1_d bottomMargin:20];
        
     
//        [btn1_c jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
//
//
//            [ZX_weakSelf removeMain];
//
//        }];
        
    }
    return _inputView;
}

- (void)on1Register  {
    [self removeMain];

    [WFCUConfigManager globalManager].selectedTheme =   2;
    

    
    WFCBaseTabBarController *tabBarVC = [WFCBaseTabBarController new];
    [UIApplication sharedApplication].delegate.window.rootViewController =  tabBarVC;
}
- (void)on2Register  {
    [self removeMain];

    [WFCUConfigManager globalManager].selectedTheme =   1;

    WFCBaseTabBarController *tabBarVC = [WFCBaseTabBarController new];
    [UIApplication sharedApplication].delegate.window.rootViewController =  tabBarVC;
}
- (void)removeMain
{

 
   [UIView animateWithDuration:0.15 animations:^{

       self.inputView.alpha = 0 ;
   } completion:^(BOOL finished) {
       self.inputView.hidden = YES;
       [self.inputView removeFromSuperview];
       self.inputView  = nil;

   }];
}
@end
